package com.qifei.xmlg_backend.service.impl;

import com.alibaba.excel.EasyExcel;
import com.qifei.xmlg_backend.DTO.emp.EmpExcelDto;
import com.qifei.xmlg_backend.DTO.student.StudentExcelDto;
import com.qifei.xmlg_backend.entity.Emp;
import com.qifei.xmlg_backend.entity.ErrorCode;
import com.qifei.xmlg_backend.entity.Student;
import com.qifei.xmlg_backend.exception.CustomException;
import com.qifei.xmlg_backend.mapper.StudentMapper;
import com.qifei.xmlg_backend.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 学生表 服务实现类
 * </p>
 *
 * @author qifei
 * @since 2025-06-11
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    private final StudentMapper studentMapper;

    public StudentServiceImpl(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public void importExcel(MultipartFile file) {
        try {
            List<StudentExcelDto> list = EasyExcel.read(file.getInputStream(), StudentExcelDto.class, null)
                    .sheet().doReadSync();
            for (StudentExcelDto dto : list) {
                Student stu = new Student();
                stu.setId(dto.getId());
                stu.setName(dto.getName());
                stu.setGender("男".equals(dto.getGender()) ? 1 : "女".equals(dto.getGender()) ? 2 : null);
                stu.setImage(dto.getImage());
                stu.setBirthDate(parseDate(dto.getBirthDate()));
                stu.setJoinDate(parseDate(dto.getJoinDate()));
                stu.setClassId(dto.getClassId());
                stu.setStatus("在读".equals(dto.getStatus()) ? 1 : "已离开".equals(dto.getStatus()) ? 0 : null);
                stu.setUpdateTime(LocalDateTime.now());

                if (stu.getId() != null && studentMapper.selectById(stu.getId()) != null) {
                    this.updateById(stu);
                } else {
                    this.save(stu);
                }
            }
        } catch (Exception e) {
            log.error("学生导入失败: " + e.getMessage());
            throw new CustomException(ErrorCode.SERVER_ERROR);
        }
    }

    @Override
    public void exportSelected(List<Integer> ids, HttpServletResponse response) {
        List<Student> students = studentMapper.selectBatchIds(ids);

        List<StudentExcelDto> exportList = students.stream().map(stu -> {
            StudentExcelDto dto = new StudentExcelDto();
            dto.setId(stu.getId());
            dto.setName(stu.getName());
            dto.setGender(stu.getGender() != null ? (stu.getGender() == 1 ? "男" : "女") : "");
            dto.setImage(stu.getImage());
            dto.setBirthDate(stu.getBirthDate() != null ? stu.getBirthDate().toString() : "");
            dto.setJoinDate(stu.getJoinDate() != null ? stu.getJoinDate().toString() : "");
            dto.setClassId(stu.getClassId());
            dto.setStatus(stu.getStatus() != null ? (stu.getStatus() == 1 ? "在读" : "已离开") : "");
            return dto;
        }).toList();

        try {
            String fileName = URLEncoder.encode("学生信息.xlsx", StandardCharsets.UTF_8);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

            EasyExcel.write(response.getOutputStream(), StudentExcelDto.class)
                    .sheet("学生信息")
                    .doWrite(exportList);

        } catch (Exception e) {
            log.error("学生导出失败: " + e.getMessage());
            throw new CustomException(ErrorCode.SERVER_ERROR);
        }
    }

    private LocalDate parseDate(String dateStr) {
        if (dateStr == null || dateStr.isBlank()) return null;
        DateTimeFormatter[] patterns = {
                DateTimeFormatter.ofPattern("yyyy/MM/dd"),
                DateTimeFormatter.ofPattern("yyyy-MM-dd"),
                DateTimeFormatter.ofPattern("yyyy-M-d")
        };
        for (DateTimeFormatter pattern : patterns) {
            try {
                return LocalDate.parse(dateStr, pattern);
            } catch (Exception ignored) {}
        }
        throw new RuntimeException("无法解析日期: " + dateStr);
    }

        @Override
    public Map<String, Object> getStudentGenderStats() {
        List<Map<String, Object>> stats = studentMapper.getStudentGenderStats();
        
        List<String> labels = new ArrayList<>();
        List<Integer> values = new ArrayList<>();
        
        for (Map<String, Object> stat : stats) {
            Integer gender = (Integer) stat.get("gender");
            Long count = (Long) stat.get("count");
            
            // 性别: 1 男, 2 女
            if (gender == 1) {
                labels.add("男");
            } else if (gender == 2) {
                labels.add("女");
            } else {
                labels.add("未知");
            }
            
            values.add(count.intValue());
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("labels", labels);
        result.put("values", values);
        
        return result;
    }

    @Override
    public Map<String, Object> getStudentStatusStats() {
        List<Map<String, Object>> stats = studentMapper.getStudentStatusStats();
        
        List<String> labels = new ArrayList<>();
        List<Integer> values = new ArrayList<>();
        
        for (Map<String, Object> stat : stats) {
            Integer status = (Integer) stat.get("status");
            Long count = (Long) stat.get("count");
            
            // 状态: 1 在读, 0 已离开
            if (status == 1) {
                labels.add("在读");
            } else if (status == 0) {
                labels.add("已离开");
            } else {
                labels.add("未知");
            }
            
            values.add(count.intValue());
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("labels", labels);
        result.put("values", values);
        
        return result;
    }

    @Override
    public Map<String, Object> getStudentJoinDateStats() {
        List<Map<String, Object>> stats = studentMapper.getStudentJoinDateStats();
        
        // 初始化12个月的数据
        List<String> months = Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月");
        Integer[] counts = new Integer[12];
        Arrays.fill(counts, 0);
        
        // 填充实际数据
        for (Map<String, Object> stat : stats) {
            Integer month = (Integer) stat.get("month");
            Long count = (Long) stat.get("count");
            
            // 月份从1开始，数组索引从0开始
            if (month >= 1 && month <= 12) {
                counts[month - 1] = count.intValue();
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("months", months);
        result.put("counts", Arrays.asList(counts));
        
        return result;
    }
}
